import React, { useEffect, useRef, useState } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver/theme.min.js';
// import 'tinymce/models/dom/model.min.js';
import 'tinymce/icons/default/icons.js';
import 'tinymce/plugins/preview/plugin.min.js';
import 'tinymce/plugins/autolink/plugin.min.js';
import 'tinymce/plugins/directionality/plugin.min.js';
import 'tinymce/plugins/visualblocks/plugin.min.js';
import 'tinymce/plugins/visualchars/plugin.min.js';
import 'tinymce/plugins/fullscreen/plugin.min.js';
import 'tinymce/plugins/image/plugin.min.js';
import 'tinymce/plugins/link/plugin.min.js';
import 'tinymce/plugins/media/plugin.min.js';
import 'tinymce/plugins/table/plugin.min.js';
import 'tinymce/plugins/pagebreak/plugin.min.js';
import 'tinymce/plugins/nonbreaking/plugin.min.js';
import 'tinymce/plugins/insertdatetime/plugin.min.js';
import 'tinymce/plugins/advlist/plugin.min.js';
import 'tinymce/plugins/lists/plugin.min.js';
import 'tinymce/plugins/wordcount/plugin.min.js';
import 'tinymce/plugins/autosave/plugin.min.js';
import 'tinymce/plugins/autoresize/plugin.min.js';
import 'tinymce/plugins/charmap/plugin.min.js';
import 'tinymce/plugins/emoticons/js/emojis.js';
import 'tinymce/plugins/emoticons/plugin.min.js';
import 'tinymce/plugins/searchreplace/plugin.min.js';
import 'tinymce/plugins/quickbars/plugin.min.js';
var storage = window.localStorage;

import useStore from '../../useStore';
import { Menu as RightMenu, Item, contextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.css';
import { Button, Modal } from 'antd';
const MENU_ID = 'tinymce-id';
const ContractEditor = (props) => {
  const [content, setContent] = useState(props.initValue);
  const [previewContent, setPreviewContent] = useState('');
  const { setnowroute, collapsed } = useStore();
  const [open, setOpen] = useState(false);
  const [variables, setVariables] = useState(props.variables);
  const editorRef = useRef(null);

  useEffect(() => {
    storage.tinymce_content = JSON.stringify(props.initValue);
    setContent(props.initValue);
  }, [props.initValue]);

  useEffect(() => {
    setVariables(props.variables);
  }, [props.variables]);
  // 撤销
  const handleUndo = (event) => {
    const editor = tinymce.activeEditor;
    if (editor) {
      const content = editor.getContent();
      storage.tinymce_content = JSON.stringify(content);
      // console.log('Undo content:', content);
    }
  };

  // 重做
  const handleUndoRedo = (event) => {
    const editor = tinymce.activeEditor;
    if (editor) {
      const content = editor.getContent();
      storage.tinymce_content = JSON.stringify(content);
      // console.log('Content after undo/redo:', content);
    }
  };

  const handleEditorChange = (content, editor) => {
    // console.log(content, "content");
    // setContent(content.level.content);
    storage.tinymce_content = JSON.stringify(content.level.content);
    // props.onChange(content.level.content);
  };

  const getContent = () => {
    setOpen(true);
    let newContent = JSON.parse(storage.tinymce_content);
    //${a} 将所有${a}替换成a的值
    for (let i = 0; i < variables.length; i++) {
      let variName = variables[i].label;
      let variValue = variables[i].value;
      //将b中的${variName}替换成variValue
      let regexString = `\\$\\{${variName}\\}(&nbsp;?.)*`;// 包含前后的 \\s* 来匹配多个nbsp; 
      let match=newContent.match(regexString);
      let nbspCount=countNbsp(match[0]);//计算nbsp; 的个数
      // console.log(nbspCount, "nbspCount");
      // console.log(variValue.length, "variValue.length");
      let replaceString=variValue;
      let num=nbspCount-variValue.length;
      for (let index = 0; index < num-3; index++) {
        replaceString+="&emsp;";
      }
      replaceString+="&ensp;"
      // console.log(replaceString);
      let finalRegex = new RegExp(regexString, 'g'); // 创建正则表达式对象
      newContent = newContent.replace(finalRegex, replaceString);
      // console.log(newContent, "22");
    }
    // console.log(newContent, "newContent");
    setPreviewContent(newContent);
  };
                
  const handleInsertVariable = (variable) => {
    const editor = tinymce.activeEditor;
    if (editor) {
      editor.insertContent('${' + variable.label + '}');
    }
  };

  function countNbsp(input) {
    const nbspMatches = input.match(/&nbsp;/g);
    return nbspMatches ? nbspMatches.length : 0;
  }

  const handleContextMenu = (event) => {
    // console.log(event);
    event.preventDefault();
    contextMenu.show({
      id: MENU_ID,
      event: event,
    });
  };

  return (
    <div>
      <Editor
        ref={editorRef}
        // id="tinymces"
        onContextMenu={handleContextMenu}
        initialValue={content}
        init={{
          language_url: 'http://111.77.154.58:2233/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          max_height: 600,
          min_height: 500,
          skin_url: 'http://111.77.154.58:2233/tinymce/skins/ui/oxide',
          content_css: 'http://111.77.154.58:2233/tinymce/skins/ui/oxide',
          promotion: false, // 隐藏更新信息
          branding: false, // 隐藏版权信息
          menubar: true,  // 显示菜单栏
          contextmenu: false, // 隐藏右键菜单
          plugins: 'quickbars searchreplace autolink directionality visualblocks visualchars fullscreen image link table charmap  \
                    pagebreak nonbreaking  insertdatetime advlist lists wordcount  autosave   autoresize  indent2em importword' ,
          toolbar: 'undo redo | quickbars forecolor backcolor bold italic underline strikethrough link anchor importword | \
                    alignleft aligncenter alignright alignjustify outdent indent2em | \
                    styleselect formatselect fontselect fontsizeselect | bullist numlist | subscript superscript removeformat | \
                    table image  charmap emoticons  pagebreak insertdatetime print  | fullscreen',
          external_plugins: {
            'wordcount': 'http://111.77.154.58:2233/tinymce/plugins/wordcount/plugin.min.js',
            'importword': 'http://111.77.154.58:2233/tinymce/plugins/importword/plugin.min.js',
            'indent2em': 'http://111.77.154.58:2233/tinymce/plugins/indent2em/plugin.min.js',
          },
          importword_handler: function(editor,files,next){
            console.log('11111111111');
            var file_name = files[0].name
            if(file_name.substr(file_name.lastIndexOf(".")+1)=='docx'){
                editor.notificationManager.open({
                    text: '正在转换中...',
                    type: 'info',
                    closeButton: false,
                });
                 next(files);
            }else{
                editor.notificationManager.open({
                    text: '目前仅支持docx文件格式，若为doc，请将扩展名改为docx',
                    type: 'warning',
                });
            }
            // next(files);
          },
          importword_filter: function(result,insert,message){ 
            // 自定义操作部分
            insert(result) //回插函数
          },
          autosave_ask_before_unload: true, // 在离开页面时询问是否保存
          setup: (editor) => {
            editor.on('Undo', handleUndo);
            editor.on('Redo', handleUndoRedo);
          },
        }}
        onChange={(e, editor) => handleEditorChange(e, editor)} // 监听编辑器内容变化事件，并调用处理函数
      />
      <Button onClick={() => getContent()} style={{marginBottom:"1vw",marginTop:"1vw"}}>预览</Button>
      <Modal open={open} onCancel={() => setOpen(false)} bodyStyle={{ width: "210mm" }} width='210mm'>
        <div style={{ height: "100%", width: "100%" }} dangerouslySetInnerHTML={{ __html: previewContent }} />
      </Modal>
      {props.variables.length > 0 &&
        <RightMenu style={{ position: "absolute", top: "30vh" }} id={MENU_ID}>
          {variables.map((variable, index) => (
            <Item key={index} onClick={() => handleInsertVariable(variable)}>
              {variable.label}
            </Item>
          ))}
        </RightMenu>
      }
    </div>
  );
};

export default ContractEditor;